In this article, we will discuss arrays as a data structure. Arrays are one of the most fundamental data structures in all programming languages. In languages such as Python, arrays are considered part of a list and hence a data structure. So, for this article, I'll be utilizing C to implement this data structure. Arrays, like lists, are useful for storing a huge quantity of information.
Arrays are similar to lists in that they are collections of items, but all of the objects' data types must be identical. An array's data or objects are kept continuously in memory, hence they are said to be stored in contiguous memory locations.
We'll start with the most basic initialization in C: using the list data type. In case you're unfamiliar with C, I'll explain everything. To define a variable in C, first give the data type, such as int, char, float, etc., followed by the variable name. Since we are defining a list, we may either leave the length blank or put it in square brackets. The array's items can then be specified. The entire process is shown below:
We have defined one-dimensional arrays. Arrays can have numerous dimensions, such as 2-dimensional arrays, which can be represented as a table, and 3-dimensional arrays. Square brackets can be used to access elements in an array. Because arrays are changeable, their elements can be altered. The following illustrates how to define and retrieve a 2-D matrix's elements:
There are various operations which can be done on an array, like Creation, Display, Search, Insertion, Deletion, Updating. Basic instances of creation and updating have been shown to us. Displaying an array is essentially looping through it and writing each item. This is seen below.
The Time and Space Complexity is O(n), which means that every element is visited and stored. Searching for an Element is done with either a for loop or a while loop. This function is shown below.
There are three cases for time complexity. The best case is O(1), which means the first item is the element you are looking for. The Worst case is O(n), which means the whole array needs to be searched and the element is found at the end of the array. The average case is that the element can be anywhere in the array, which would also be denoted as O(n). the space complexity is O(n).
For Insertion and deletion of the array, I will first show the code and then explain it. The time complexity for both is O(n)
First, we free up the index by moving each element ahead until we reach the index where we need to insert the element. This was accomplished using step 1 as quoted in the code. Next, in step 2, we store the new element where we intended to introduce it. As demonstrated in step 3, we update the total element. Deletion works in a similar way.
This concludes the article. You may find the finished source code on my GitHub page.